package com.tgpms.web.earlierStage.service.impl;

import java.math.BigDecimal;
import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tgpms.common.Result;
import com.tgpms.exception.ExceptionExplain;
import com.tgpms.exception.InsertException;
import com.tgpms.util.Common;
import com.tgpms.util.FTPUtil;
import com.tgpms.web.earlierStage.dao.DocSortMapper;
import com.tgpms.web.earlierStage.dao.DocSortTemplateMapper;
import com.tgpms.web.earlierStage.dao.DocUploadEntityMapper;
import com.tgpms.web.earlierStage.dao.TaskDefinitionMapper;
import com.tgpms.web.earlierStage.dao.TaskJournalMapper;
import com.tgpms.web.earlierStage.entity.DocSort;
import com.tgpms.web.earlierStage.entity.DocSortTemplate;
import com.tgpms.web.earlierStage.entity.DocUploadEntity;
import com.tgpms.web.earlierStage.entity.TaskDefinition;
import com.tgpms.web.earlierStage.entity.TaskJournal;
import com.tgpms.web.earlierStage.service.EarlierTaskDefinService;

@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
public class EarlierTaskDefinServiceImpl implements EarlierTaskDefinService {

	private final Logger log = LoggerFactory.getLogger(EarlierTaskDefinServiceImpl.class);
	@Autowired
	private TaskDefinitionMapper taskDefinitionMapper;
	@Autowired
	private DocSortTemplateMapper docSortTemplateMapper;
	@Autowired
	private TaskJournalMapper taskJournalMapper;
	@Autowired
	private DocSortMapper docSortMapper;
	@Autowired
	private DocUploadEntityMapper docUploadEntityMapper;
	
	//ftp_url
	@Value("${ftpparam.url}")
	private String url;
	@Value("${ftpparam.port}")
	private Integer port;
	@Value("${ftpparam.username}")
	private String username;
	@Value("${ftpparam.password}")
	private String password;
	@Value("${ftpparam.downurl}")
	private String downurl;
	@Value("${ftpparam.filepath3}")
	private String filepath3;

	@Override
	public synchronized Result addTaskDefin(TaskDefinition taskDefin, Result result) {
		if(Common.isEmpty(taskDefin.getBeforeTask())) {
			taskDefin.setBeforeTask("0");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		//判断增加的是父级任务还是子任务
		if(Common.isEmpty(taskDefin.getParentId())) {
			taskDefin.setParentId("0");
			//父任务
			map.put("parentId", "0");
			map.put("projectId", taskDefin.getProjectId());
			map.put("orderby", " order by TASK_CODE desc");
			List<TaskDefinition> list = taskDefinitionMapper.selTaskDefinition(map);
			String code = "0";
			if(list==null || list.size()==0) {
				code = "01";
			}else {
				int i = Integer.parseInt(list.get(0).getTaskCode())+1;
				if(i<10) {
					code = "0"+i;
				}else {
					code = i+"";
				}
			}
			taskDefin.setTaskCode(code);
		}
		else {
			//子任务
			TaskDefinition defin = taskDefinitionMapper.selectByPrimaryKey(taskDefin.getParentId());
			if(defin==null) {
				result.setSuccess(false);
				result.setMsg(ExceptionExplain.ERROR_BY_INSERT.getExplain()+"|父任务为空");
				return result;
			}
			else {
				/**
				 * 自动编码
				 */
				String parentCode = defin.getTaskCode();
				map.clear();
				map.put("taskCodelike", parentCode);
				map.put("taskCodeno", parentCode);
				map.put("projectId", taskDefin.getProjectId());
				map.put("orderby", " order by TASK_CODE desc");
				List<TaskDefinition> list2 = taskDefinitionMapper.selTaskDefinition(map);
				String code = "0";
				if(list2==null || list2.size()==0) {
					code=parentCode+"01";
				}else {
					int i = parentCode.length();
					StringBuilder taskcode = new StringBuilder(list2.get(0).getTaskCode());
					int k = Integer.parseInt(taskcode.replace(0, i,"").toString())+1;
					String c = "";
					if(k<10) {
						c = "0"+k;
					}else {
						c = ""+k;
					}
					code = parentCode+c;
				}
				taskDefin.setTaskCode(code);
			}
		}
		//主键形式 yyyyMMddHHmmss+UUID 
		taskDefin.setId(Common.fromDateFormats()+UUID.randomUUID().toString().replaceAll("-", "").toUpperCase());
		taskDefin.setRowstamp(taskDefin.getId());
		taskDefin.setInsertDate(new Date());
		int i = taskDefinitionMapper.insertSelective(taskDefin);
		if(i==1) {
			result.setMsg(ExceptionExplain.SUCCESS_BY_INSERT.getExplain());
			result.setData(taskDefin.getId());
		}else {
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_INSERT.getExplain());
		}
		return result;
	}
	
	@Override
	public Result updateTaskDefin(TaskDefinition taskDefin, Result result) {
		taskDefin.setModifyDate(new Date());
		int i = taskDefinitionMapper.updateByPrimaryKeySelective(taskDefin);
		if(i==1) {
			result.setMsg(ExceptionExplain.SUCCESS_BY_UPDATE.getExplain());
		}else {
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_UPDATE.getExplain());
		}
		return result;
	}

	@Override
	public Result deleteTaskDefin(String id,Result result) {
		try {
			//主键查询
			TaskDefinition taskDefin = taskDefinitionMapper.selectByPrimaryKey(id);
			//查询下级任务集合
			Map<String, Object> map2 = new HashMap<String, Object>();
			map2.put("taskCodelike", taskDefin.getTaskCode());
			map2.put("projectId", taskDefin.getProjectId());
			List<TaskDefinition> list = taskDefinitionMapper.selTaskDefinition(map2);
			if(list!=null && list.size()>0) {
				for(TaskDefinition task : list) {
					//删除任务
					taskDefinitionMapper.deleteByPrimaryKey(task.getId());
					//删除对应所有文档
					Map<String, Object> map1 = new HashMap<String, Object>();
					map1.put("taskId", task.getId());
					List<DocUploadEntity> docList2 = docUploadEntityMapper.getDocUploadEntity(map1);
					if(docList2!=null && docList2.size()>0) {
						for(DocUploadEntity doc : docList2) {
							FTPUtil.deleteFile(url, port, username, password, doc.getFilePath(), doc.getNewDocName());
						}
					}
					//删除文件分类
					docSortMapper.deleteDocSortById(task.getId());
					//删除日志信息
					taskJournalMapper.deleteByid(task.getId());
				}
			}
			result.setMsg(ExceptionExplain.SUCCESS_BY_DELETE.getExplain());
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_DELETE.getExplain());
		}
		return result;
	}
	

	@Override
	public List<Object> selTaskDefin(String id, String projectId) {
		//查询第一层
		List<Object> list = new ArrayList<Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		if(!Common.isEmpty(id)) {
			map.put("parentId", id);
		}else {
			map.put("parentId", "0");
		}
		if(!Common.isEmpty(projectId)) {
			map.put("projectId", projectId);
		}
		map.put("orderby", " order by td.TASK_CODE asc");
		List<TaskDefinition> onelist = taskDefinitionMapper.selTaskDefinitionForTree(map); 
		if(onelist!=null && onelist.size()>0) {
			for(TaskDefinition temp : onelist) {
				JSONObject tempJson = (JSONObject) JSONObject.toJSON(temp);
				tempJson.remove("insertUser");
				tempJson.remove("insertDate");
				tempJson.remove("modifyUser");
				tempJson.remove("modifyDate");
				tempJson.remove("rowstamp");
				Map<String, Object> map1 = new HashMap<String, Object>();
				map1.put("parentId", temp.getId());
				if(!Common.isEmpty(projectId)) {
					map1.put("projectId", projectId);
				}
				map1.put("orderby", " order by td.TASK_CODE asc");
				List<Object> children = getChilren(map1);
				tempJson.put("children", children);

				list.add(tempJson);
			}
		}
		return list;
	}

	private List<Object> getChilren(Map<String, Object> map){
		List<Object> list = new ArrayList<Object>();
		List<TaskDefinition> onelist = taskDefinitionMapper.selTaskDefinitionForTree(map); 
		if(onelist!=null && onelist.size()>0) {
			for(TaskDefinition temp : onelist) {
				JSONObject tempJson = (JSONObject) JSONObject.toJSON(temp);
				tempJson.remove("insertUser");
				tempJson.remove("insertDate");
				tempJson.remove("modifyUser");
				tempJson.remove("modifyDate");
				tempJson.remove("rowstamp");
				Map<String, Object> map1 = new HashMap<String, Object>();
				map1.put("parentId", temp.getId());
				List<Object> children = getChilren(map1);
				tempJson.put("children", children);
				list.add(tempJson);
			}
		}
		return list;
	}
	
	
	@Override
	public List<Object> selTaskDefinByArs(String id,String projectId) {
		//查询第一层
		List<Object> list = new ArrayList<Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		if(!Common.isEmpty(id)) {
			map.put("parentId", id);
		}else {
			map.put("parentId", "0");
		}
		if(!Common.isEmpty(projectId)) {
			map.put("projectId", projectId);
		}
		map.put("orderby", " order by td.TASK_CODE asc");
		List<TaskDefinition> onelist = taskDefinitionMapper.selTaskDefinitionForTree(map); 
		if(onelist!=null && onelist.size()>0) {
			for(TaskDefinition temp : onelist) {
				JSONObject tempJson = (JSONObject) JSONObject.toJSON(temp);
				Map<String, Object> map1 = new HashMap<String, Object>();
				map1.put("parentId", tempJson.getString("id"));
				if(!Common.isEmpty(projectId)) {
					map1.put("projectId", projectId);
				}
				map1.put("orderby", " order by td.TASK_CODE asc");
				List<Object> children = getChilrenByArs(map1);
				if(children!=null && children.size()>0) {
					tempJson.put("hasChildren", true);
				}
				list.add(tempJson);
			}
		}
		return list;
	}
	
	//异步加载子集
	private List<Object> getChilrenByArs(Map<String, Object> map){
		List<Object> list = new ArrayList<Object>();
		List<TaskDefinition> onelist = taskDefinitionMapper.selTaskDefinitionForTree(map); 
		if(onelist!=null && onelist.size()>0) {
			for(TaskDefinition temp : onelist) {
				JSONObject tempJson = (JSONObject) JSONObject.toJSON(temp);
				list.add(tempJson);
			}
		}
		return list;
	}
	

	//任务模板导入
	@Override
	public synchronized Result taskTempImport(String listStr,String projectId,String insertName,Result result) {
		//查询任务分解编码最大值
		Map<String, Object> tmap = new HashMap<String, Object>();
		tmap.put("parentId", "0");
		tmap.put("projectId", projectId);
		tmap.put("orderby", " order by TASK_CODE desc");
		List<TaskDefinition> tasklist = taskDefinitionMapper.selTaskDefinition(tmap);
		String code = "0";
		if(tasklist==null || tasklist.size()==0) {
			code = "01";
		}else {
			int i = Integer.parseInt(tasklist.get(0).getTaskCode())+1;
			if(i<10) {
				code = "0"+i;
			}else {
				code = i+"";
			}
		}
		//解析listStr,转换主键,编码,父ID
		List<Map<String,Object>> list = JSONArray.parseObject(listStr,List.class);
		for(Map<String,Object> map : list) {
			String taskcode = map.get("TASK_CODE").toString();
			String oldcode = taskcode.substring(0, 2);
			map.put("TASK_CODE", taskcode.replaceFirst(oldcode, code));
			String taskId = map.get("TASK_ID").toString();
			map.put("OLD_TASK_ID", taskId);
			String newTaskId = Common.fromDateFormats()+UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
			map.put("TASK_ID", newTaskId);
			map.put("ROWSTAMP", newTaskId);
			for(Map<String,Object> map1 : list) {
				if(map1.get("BEFORE_TASK").toString().equals(taskId)) {
					map1.put("BEFORE_TASK", newTaskId);
				}
				if(map1.get("PARENT_ID").toString().equals(taskId)) {
					map1.put("PARENT_ID", newTaskId);
				}
			}
		}
		int i=-1;
		//循环插入任务分解表
		for(Map<String,Object> map2 : list) {
			TaskDefinition taskDefin = new TaskDefinition();
			taskDefin.setId(map2.get("TASK_ID").toString());
			taskDefin.setProjectId(projectId);
			taskDefin.setTaskCode(map2.get("TASK_CODE").toString());
			taskDefin.setTaskDesc(map2.get("TASK_DESC").toString());
			taskDefin.setTaskLevel(map2.get("TASK_LEVEL").toString());
			taskDefin.setRatio(new BigDecimal(map2.get("RATIO").toString()));
			taskDefin.setParentId(map2.get("PARENT_ID").toString());
			taskDefin.setBeforeTask(map2.get("BEFORE_TASK").toString());
			taskDefin.setBeforeTaskType(map2.get("BEFORE_TASK_TYPE").toString());
			taskDefin.setStatus(map2.get("STATUS").toString());
			taskDefin.setInsertUser(insertName);
			taskDefin.setInsertDate(new Date());
			taskDefin.setRowstamp(map2.get("ROWSTAMP").toString());
			if(map2.get("IF_IGNORE")!=null) {
				taskDefin.setIfIgnore(map2.get("IF_IGNORE").toString());
			}
			if(map2.get("NEEDED_MATERIAL")!=null) {
				taskDefin.setNeededMaterial(map2.get("NEEDED_MATERIAL").toString());
			}
			if(map2.get("NEEDED_TIME")!=null) {
				taskDefin.setNeededTime(map2.get("NEEDED_TIME").toString());
			}
			if(map2.get("APPROVAL_COMPANY")!=null) {
				taskDefin.setApprovalCompany(map2.get("APPROVAL_COMPANY").toString());
			}
			if(map2.get("REPORT_PERSON")!=null) {
				taskDefin.setReportPerson(map2.get("REPORT_PERSON").toString());
			}
			if(map2.get("SUPERVISE_NOTE")!=null) {
				taskDefin.setSuperviseNote(map2.get("SUPERVISE_NOTE").toString());
			}
			if(map2.get("PROJECT_DEPT")!=null) {
				taskDefin.setSuperviseNote(map2.get("PROJECT_DEPT").toString());
			}
			if(map2.get("GOV_INFO")!=null) {
				taskDefin.setSuperviseNote(map2.get("GOV_INFO").toString());
			}
			if(map2.get("FRUIT_INFO")!=null) {
				taskDefin.setSuperviseNote(map2.get("FRUIT_INFO").toString());
			}
			if(map2.get("OTHER_INFO")!=null) {
				taskDefin.setSuperviseNote(map2.get("OTHER_INFO").toString());
			}
			
			if(!Common.isEmpty(map2.get("TO_USERS"))) {
				taskDefin.setToUsers(map2.get("TO_USERS").toString());
			}
			if(!Common.isEmpty(map2.get("TO_GROUPS"))) {
				taskDefin.setToGroups(map2.get("TO_GROUPS").toString());
			}
			if(!Common.isEmpty(map2.get("DATA_OWNER"))) {
				taskDefin.setDataOwner(map2.get("DATA_OWNER").toString());
			}
			taskDefin.setTemplateId(map2.get("TASK_ID").toString());
//			//导入模板时默认责任人为当前用户
//			taskDefin.setPersonLiable(insertName);
			i = taskDefinitionMapper.insertSelective(taskDefin);
			//将对应的文档模板导入文档分类表
			Map<String,Object> map3 = new HashMap<String, Object>();
			map3.put("taskId", map2.get("OLD_TASK_ID").toString());
			List<DocSortTemplate> doctemplist = docSortTemplateMapper.selDocSortTemplate(map3);
			if(doctemplist!=null && doctemplist.size()>0) {
				for(DocSortTemplate temp : doctemplist) {
					DocSort docSort = new DocSort();
					docSort.setId(map2.get("TASK_ID").toString());
					docSort.setRowstamp(docSort.getId());
					docSort.setProjectId(projectId);
					docSort.setSortId(Common.fromDateFormats()+UUID.randomUUID().toString().replaceAll("-", "").toUpperCase());
					docSort.setDocRequire(temp.getDocRequire());
					docSort.setDocLevel(temp.getDocLevel());
					docSort.setFruitYn(temp.getFruitYn());
					docSort.setInsertUser(insertName);
					docSort.setInsertDate(new Date());
					if(!Common.isEmpty(map2.get("TO_USERS"))) {
						docSort.setToUsers(map2.get("TO_USERS").toString());
					}
					if(!Common.isEmpty(map2.get("TO_GROUPS"))) {
						docSort.setToGroups(map2.get("TO_GROUPS").toString());
					}
					if(!Common.isEmpty(map2.get("DATA_OWNER"))) {
						docSort.setDataOwner(map2.get("DATA_OWNER").toString());
					}
					i = docSortMapper.insertSelective(docSort);
				}
			}
		}
		if(i==1) {
			result.setMsg(ExceptionExplain.SUCCESS_BY_INSERT.getExplain());
		}else {
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_INSERT.getExplain());
			throw new InsertException(ExceptionExplain.ERROR_BY_INSERT.getExplain());
		}
		return result;
	}

	@Override
	public Result launchTask(String id, String modifyUser) {
		Result result = new Result();
		TaskDefinition taskDefinition = taskDefinitionMapper.selectByPrimaryKey(id);
		if (taskDefinition != null) {
			if ("O".equals(taskDefinition.getStatus())) {
				taskDefinition.setStatus("B");
			}
			taskDefinition.setModifyUser(modifyUser);
			taskDefinition.setModifyDate(new Date());
			int i = taskDefinitionMapper.updateByPrimaryKeySelective(taskDefinition);
			if (i == 1) {
				result = updateStatus(id,modifyUser);
			} else {
				result.setSuccess(false);
				result.setMsg(ExceptionExplain.ERROR_BY_UPDATE.getExplain());
			}
		} else {
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.EMPTY_BY_DATA.getExplain());
		}
		return result;
	}

	@Override
	public List<Map<String, Object>> selReportTable(Map<String, Object> map) {

		List<Map<String, Object>> list1 = new ArrayList<Map<String,Object>>();
		list1 = taskDefinitionMapper.selReportTable(map);
		return list1;
	}

	/**
	 * @Author guan
	 * @Description 用于查询子节点数据，更新状态
	 * @Date 17:43 2019-12-6
	 * @Param []
	 * @return java.util.List<com.tgpms.web.earlierStage.entity.TaskDefinition>
	 **/
	public Result updateStatus(String id, String modifyUser) {
		Result result = new Result();
		Map<String, Object> map = new HashMap<String, Object>();
		if(!Common.isEmpty(id)) {
			map.put("parentId", id);
		}else {
			map.put("parentId", "0");
		}
		List<TaskDefinition> taskDefinitionList = taskDefinitionMapper.selTaskDefinition(map);
		for (Iterator<TaskDefinition> it = taskDefinitionList.iterator(); it.hasNext();) {
			TaskDefinition taskDefinition = it.next();
			if ("O".equals(taskDefinition.getStatus())) {
				taskDefinition.setStatus("B");
			}
			taskDefinition.setModifyUser(modifyUser);
			taskDefinition.setModifyDate(new Date());
			int i = taskDefinitionMapper.updateByPrimaryKeySelective(taskDefinition);
			if (i == 1) {
				result.setData(i);
				result.setSuccess(true);
				result.setMsg(ExceptionExplain.SUCCESS_BY_UPDATE.getExplain());
				this.updateStatus(taskDefinition.getId(), modifyUser);
			} else {
				result.setData(i);
				result.setSuccess(false);
				result.setMsg(ExceptionExplain.ERROR_BY_UPDATE.getExplain());
				break;
			}
		}
		return result;
	}
	
	
	@Override
	public void lixiang() {
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("taskDesc", "项目采购");
		List<TaskDefinition> list = taskDefinitionMapper.selTaskDefinition(map);
//		log.info("查询的结果为："+list.toString());
		for(TaskDefinition taskDefin : list) {
			log.info("当前循环的任务为："+taskDefin.toString());
			TaskDefinition task = new TaskDefinition();
			task.setId(Common.fromDateFormats()+UUID.randomUUID().toString().replaceAll("-", "").toUpperCase());
			task.setProjectId(taskDefin.getProjectId());
			task.setTaskDesc("取得项目中标通知书");
			task.setDivision(taskDefin.getDivision());
			task.setPersonLiable(taskDefin.getPersonLiable());
			task.setTaskLevel("A");
			task.setRatio(new BigDecimal("100"));
			task.setBeforeTask(taskDefin.getId());
			task.setBeforeTaskType(taskDefin.getBeforeTaskType());
			task.setRemarks(taskDefin.getRemarks());
			task.setRelationPartner(taskDefin.getRelationPartner());
			task.setStatus("B");
			task.setInsertUser(taskDefin.getInsertUser());
			task.setInsertDate(taskDefin.getInsertDate());
			task.setRowstamp(task.getId());
			task.setParentId(taskDefin.getId());
			task.setTaskCode(taskDefin.getTaskCode()+"11");
			int i = taskDefinitionMapper.insertSelective(task);
			if(i==1) {
				log.info("项目采购任务增加取得项目中标通知书节点成功");
			}else {
				log.info("项目采购任务增加取得项目中标通知书节点失败");
			}
			
			TaskJournal taskJou = new TaskJournal();
			taskJou.setId(task.getId());
			String id = taskJou.getId();
			taskJou.setProjectId(task.getProjectId());
			taskJou.setJournalDesc("汇总");
			taskJou.setPersonLiable("无");
			taskJou.setDispute("N");
			taskJou.setStauts("0");
			taskJou.setInsertUser("汇总人");
			String parentid = "";
			while(true) {
				//查询父级id
				TaskDefinition taskDefinition = taskDefinitionMapper.selectByPrimaryKey(id);
				if(taskDefinition==null) {
					break;
				}
				parentid = taskDefinition.getParentId();
				if(parentid.equals("0")) {
					break;
				}else {
					id = parentid;
					String Ratios = taskJournalMapper.getParentRatios(parentid);
					int yRatios = taskJournalMapper.getParentYRatios(parentid);
					BigDecimal decimal = new BigDecimal(Ratios);
					if(yRatios>0) {
						decimal = decimal.add(new BigDecimal(yRatios+""));
					}
					int count = taskJournalMapper.getParentCounts(parentid);
					decimal = decimal.divide(new BigDecimal(count+""),2,BigDecimal.ROUND_UP);
					System.out.println("#################计算的百分比为："+decimal);
					taskJournalMapper.deleteByid(id);
					taskJou.setRatio(decimal);
					taskJou.setId(id);
					taskJou.setJournalId(Common.fromDateFormats()+UUID.randomUUID().toString().replaceAll("-", "").toUpperCase());
					taskJou.setRowstamp(taskJou.getJournalId());
					taskJou.setInsertDate(new Date());
					taskJournalMapper.insertSelective(taskJou);
				}
			}
		}
		
	}


}
